//
//  CatogryStrategyViewController.m
//  project
//
//  Created by lanou on 15/10/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "CatogryStrategyViewController.h"
#import "StrategyCollectionViewCell.h"
#import "CatogryHeaderCollectionReusableView.h"
#import "CatogryHeaderTitleView.h"
#import "PKRequestManager.h"
#import "CatogryStrategyHeaderModel.h"
#import "CatogryStrategyItemsModel.h"
#import "CatogryAllSpecialViewController.h"
#import "CatogryItemDetailViewController.h"
#import "FMDatabase.h"
@interface CatogryStrategyViewController () <UICollectionViewDataSource,UICollectionViewDelegate>
//创建一个初始的scrollView
@property(nonatomic,strong)UIScrollView *mainScrollView;

//创建界面开始的view
@property(nonatomic,strong)CatogryHeaderCollectionReusableView *headerView;

//创建collectionView
@property(nonatomic,strong)UICollectionView *strategyCollectionView;

//创建collecyionView的区头
@property(nonatomic,strong)CatogryHeaderTitleView *titleView;

//创建一个接收collectionView数据的数组
@property(nonatomic,strong)NSMutableArray *dataSourceArray;

//创建一个接收界面头的数据的数组
@property(nonatomic,strong)NSMutableArray *headerArray;

@property (nonatomic, strong)FMDatabase *dataBase;

@end

@implementation CatogryStrategyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _mainScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 70, kWidth, kHeight - 110)];
    [self.view addSubview:_mainScrollView];

    _headerView = [[CatogryHeaderCollectionReusableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 130)];

    [_headerView.seatchButton addTarget:self action:@selector(pushSpecial:) forControlEvents:(UIControlEventTouchUpInside)];
    [_headerView.firstButton addTarget:self action:@selector(pushSpecial:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.secondButton addTarget:self action:@selector(pushSpecial:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.thirdButton addTarget:self action:@selector(pushSpecial:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.forthButton addTarget:self action:@selector(pushSpecial:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.fifthButton addTarget:self action:@selector(pushSpecial:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView.sixthButton addTarget:self action:@selector(pushSpecial:) forControlEvents:UIControlEventTouchUpInside];
    _headerArray = [NSMutableArray arrayWithCapacity:0];
    [_mainScrollView addSubview:_headerView];
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((kWidth - 110) / 4, (kWidth - 110) / 4 + 30);
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    layout.minimumInteritemSpacing = 30;
    layout.minimumLineSpacing = 30;
    layout.headerReferenceSize = CGSizeMake(kWidth, 50);


    _strategyCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,140, kWidth, kHeight - 280) collectionViewLayout:layout];

    _strategyCollectionView.delegate = self;
    _strategyCollectionView.dataSource = self;
 //   [_strategyCollectionView setScrollEnabled:NO];
    _strategyCollectionView.backgroundColor = [UIColor whiteColor];
    [_strategyCollectionView registerClass:[StrategyCollectionViewCell class] forCellWithReuseIdentifier:@"StrategyCollectionViewCell"];
    [_strategyCollectionView registerClass:[CatogryHeaderTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    _dataSourceArray = [NSMutableArray arrayWithCapacity:0];
    
    [_mainScrollView addSubview:_strategyCollectionView];
    
    
            NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"project.db"];
    
        _dataBase = [FMDatabase databaseWithPath:filePath];
        //判断数据库是否打开，打开后创建catogry路径
        if ([_dataBase open])
        {
            [_dataBase executeUpdate:@"create table catogryHeader (data blob)"];
            [_dataBase executeUpdate:@"create table catogryCollection (data blob)"];
        }
        else
        {
            NSLog(@"数据库打开失败");
        }
    
        FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from catogryHeader"];
    
        while ([resultSet next])
        {
            NSData *data = [resultSet dataForColumn:@"data"];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            NSDictionary *dict = dic[@"data"];
            NSArray *headerArray = dict[@"collections"];
            for (NSDictionary *dicModel in headerArray)
            {
                CatogryStrategyHeaderModel *model = [[CatogryStrategyHeaderModel alloc]init];
                [model setValuesForKeysWithDictionary:dicModel];
                [_headerArray addObject:model];
                
            }
            
        }
    if (_headerArray.count != 0)
    {
        [_headerView setArray:_headerArray];
    }
    
    FMResultSet *resultSetCollection = [_dataBase executeQueryWithFormat:@"select * from catogryCollection"];
    
    while ([resultSetCollection next])
    {
        NSData *data = [resultSetCollection dataForColumn:@"data"];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSDictionary *dict = dic[@"data"];
        NSArray *array = dict[@"channel_groups"];
        for (NSDictionary *dicItem in array)
        {
            NSArray *array1 = dicItem[@"channels"];
            NSMutableArray *array2 = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dic1 in array1)
            {
                CatogryStrategyItemsModel *model = [[CatogryStrategyItemsModel alloc]init];
                [model setValuesForKeysWithDictionary:dic1];
                [array2 addObject:model];
            }
            [_dataSourceArray addObject:array2];
        }
        
    }
    if (_dataSourceArray.count != 0)
    {
        [_strategyCollectionView reloadData];
    }

    
    
    [self requestData];
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//push专题界面的点击方法
-(void)pushSpecial:(UIButton *)button
{
    //调用block方法
    CatogryAllSpecialViewController *specialViewController = [[CatogryAllSpecialViewController alloc]init];
    self.pushSpecial(specialViewController);
}
//第一个button到第六个button的点击方法


//返回多少个分区
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.dataSourceArray.count;
}

//返回分区里有多少个cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 15;
    }
    else if (section == 1)
    {
        return 7;
    }
    else if (section == 2)
    {
        return 8;
    }
    else
    {
        return 6;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"StrategyCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor grayColor];
    CatogryStrategyItemsModel *model = _dataSourceArray[indexPath.section][indexPath.row];
    cell.model = model;
    if (indexPath.section == 0 && indexPath.row == 0)
    {
        CGFloat collectionHight = _strategyCollectionView.contentSize.height;
        _strategyCollectionView.frame = CGRectMake(0, 140, kWidth, collectionHight);
        _mainScrollView.contentSize = CGSizeMake(kWidth, collectionHight + 160);
    }
    return cell;
}



-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    CatogryHeaderTitleView *titleView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    self.titleView = titleView;
    NSArray *arr = @[@"品类",@"对象",@"场合",@"风格"];
    self.titleView.titleLabel.text = arr[indexPath.section];
    return self.titleView;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    CatogryItemDetailViewController *itemDetailVC = [[CatogryItemDetailViewController alloc]init];
    CatogryStrategyItemsModel *model = _dataSourceArray[indexPath.section][indexPath.row];
    itemDetailVC.id = model.id;
    itemDetailVC.titleString = model.name;
    self.pushSpecial(itemDetailVC);
}

-(void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    
    [PKRequestManager requestWithTypeP:GET urlString:@"http://api.liwushuo.com/v2/collections?limit=6&offset=0" parDic:parDic finish:^(NSData *data) {
        
        [_dataBase executeUpdate:@"delete from catogryHeader"];
        [_dataBase executeUpdate:@"insert into catogryHeader (data) values (?)", data];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dict = dic[@"data"];
        NSArray *headerArray = dict[@"collections"];
        [_headerArray removeAllObjects];
        for (NSDictionary *dicModel in headerArray)
        {
            CatogryStrategyHeaderModel *model = [[CatogryStrategyHeaderModel alloc]init];
            [model setValuesForKeysWithDictionary:dicModel];
            [_headerArray addObject:model];
            
        }
        [_headerView setArray:_headerArray];
        
    } error:^(NSError *error) {
        NSLog(@"数据请求失败");
    }];
    
    [PKRequestManager requestWithTypeP:GET urlString:@"http://api.liwushuo.com/v2/channel_groups/all" parDic:parDic finish:^(NSData *data) {
        
        [_dataBase executeUpdate:@"delete from catogryCollection"];
        [_dataBase executeUpdate:@"insert into catogryCollection (data) values (?)", data];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSDictionary *dict = dic[@"data"];
        NSArray *array = dict[@"channel_groups"];
        [_dataSourceArray removeAllObjects];
        for (NSDictionary *dicItem in array)
        {
            NSArray *array1 = dicItem[@"channels"];
            NSMutableArray *array2 = [NSMutableArray arrayWithCapacity:0];
            for (NSDictionary *dic1 in array1)
            {
                CatogryStrategyItemsModel *model = [[CatogryStrategyItemsModel alloc]init];
                [model setValuesForKeysWithDictionary:dic1];
                [array2 addObject:model];
            }
            [_dataSourceArray addObject:array2];
        }
        [_strategyCollectionView reloadData];
        
        
        
    } error:^(NSError *error) {
        NSLog(@"数据请求失败");
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
